<script setup lang="ts">
import { useFormItem } from 'element-plus';
import { debugWarn } from 'element-plus/es/utils/error';
import type { IFormUploadValue, FormUploadDefineProps } from './props';
import type { UploadProps } from 'element-plus';

const props = withDefaults(defineProps<FormUploadDefineProps>(), {});

const emit = defineEmits<{
    (event: 'update:modelValue', value: IFormUploadValue): void;
}>();

const value = computed<IFormUploadValue>({
    get() {
        return props.modelValue;
    },
    set(value) {
        emit('update:modelValue', value);
    },
});

const defaultProps = {
    showFileList: false,
    autoUpload: false,
};

const defaultExtends = {
    title: '上传文件',
};

const { formItem } = useFormItem();

const onChange: UploadProps['onChange'] = (uploadFile, uploadFiles) => {
    if (typeof props.props?.onChange === 'function') {
        props.props.onChange(uploadFile, uploadFiles);
    }
    if (uploadFile.raw) {
        value.value = uploadFile.raw;
    }
};

const deleteFile = () => {
    value.value = null;
};

const extendProps = computed(() => {
    return { ...defaultExtends, ...props.extends };
});

const commProps = computed(() => {
    return { ...defaultProps, ...props.props };
});

watch(
    () => props.modelValue,
    () => {
        formItem?.validate('change').catch((err) => debugWarn(err));
    }
);
</script>

<template>
    <div class="my-form-upload">
        <el-upload v-bind="commProps" :on-change="onChange">
            <el-button>
                <el-icon :size="16"><my-icon name="upload"></my-icon></el-icon>
                <span>{{ extendProps.title || '' }}</span>
            </el-button>
        </el-upload>
        <span v-if="!!value" class="file-name-text">{{ value?.name || '' }}</span>
        <div v-else class="placeholder-text">
            {{ extendProps.placeholder || '' }}
        </div>
        <el-icon v-if="!!value" :size="16" class="file-delete" @click="deleteFile"><my-icon name="close"></my-icon></el-icon>
    </div>
</template>

<style scoped>
.my-form-upload {
    height: 32px;
    display: flex;
    gap: 12px;
    align-items: center;
}
.file-name-text {
    color: var(--el-text-color-regular);
    flex: auto;
}
.placeholder-text {
    color: var(--el-text-color-placeholder);
    flex: auto;
}
.my-form-upload:deep(> div) {
    display: flex;
}
.file-delete {
    cursor: pointer;
}
.file-delete:hover {
    color: var(--el-color-primary);
}
</style>
